// pages/my/my.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    vipFlag:false,
    vip:[],
    vipNameStr: '', // 添加新的字符串变量
    viplist:{
      vipName:[],
      discount:[],
      sendLevel:[],
      fiveC:0,
      twentyC:0
    },
    phone:'',
    uid:'',
    voucherNumber:0,
    couponNumber:0,
    color:'#282828',
    showAuthPopup: false,
    modal:false
  },

  phonecall() {
    wx.makePhoneCall({
      phoneNumber: '19705053135',
    })
  },
  hideModal(){
    this.setData({
      modal:false
    })
  },
  login(){
    wx.navigateTo({
      url: '/pages/login/login'
    })
  },
  voucher() {
    if(this.data.phone){
      wx.navigateTo({
        url: '/pages/voucher/voucher'
      })
    }else{
      this.setData({
        showAuthPopup:true,
      })
    }
    
  },
  coupon() {
    if(this.data.phone){
      wx.navigateTo({
        url: '/pages/coupon/coupon'
      })
    }else{
      this.setData({
        showAuthPopup:true,
      })
    }
  },
  address() {
    if(this.data.phone){
      this.setUser();
      wx.navigateTo({
        url: '/pages/address/address'
      })
    }else{
      this.setData({
        showAuthPopup:true,
      })
    }
  },
  setting() {
    wx.navigateTo({
      url: '/pages/setting/setting'
    })
  },
  //获取兑换券数量
  getVoucher(){
    let _this=this;
    wx.request({
      url: app.globalData.onlineUrl+'/items', 
      method: 'POST',
      data: {
        phone:_this.data.phone
      },
      success: function(res) {
        let voucherNumber=res.data.data[0].num;
        _this.setData({
          voucherNumber:voucherNumber,
          color:'#FD6800'
         })
      },
      fail: function(err) {
      },
      complete: function() {}
    });
  },
  getCouponNum(){
    let _this=this;
    wx.request({
      url: app.globalData.onlineUrl+'/couponsNum', 
      method: 'POST',
      data: {
        phone:_this.data.phone
      },
      success: function(res) {
        let couponNumber=res.data.data[0].activeCount;
        _this.setData({
          couponNumber:couponNumber
         })
      },
      fail: function(err) {
      },
      complete: function() {}
    });
  },
  showModal(){
    this.setData({
      modal:true
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {    
  },
  //处理会员信息
  setUserVipInfo(vip){
    if(vip){
      let viplist={
        vipName:[],
        discount:[],
        sendLevel:[],
        fiveC:0,
        twentyC:0
      }
      vip.forEach(item => {
        viplist.vipName.push(item.vip_name)
        viplist.discount.push(item.dis_num)
        viplist.sendLevel.push(item.send_level)
        viplist.fiveC+=item.five_c
        viplist.twentyC+=item.ty_c
      });
      this.setData({
        viplist:viplist,
        vipNameStr: viplist.vipName && viplist.vipName.length ? viplist.vipName.join('、') : ''
      })
      console.log(viplist);
    }
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    app.getBuyCarNum()
    this.getTabBar().setData({
      PageCur: 'my'
    })
    this.setData({
      phone:wx.getStorageSync('phone'),
      uid:wx.getStorageSync('uid')
    })
    this.getVoucher();
    this.getCouponNum();
    if(wx.getStorageSync('phone')){
      this.getUserVip()
    }
  },
  getUserVip(){
    let _this=this;
    wx.request({
      url:app.globalData.onlineUrl+"/getUserVip",
      header:{'content-type': 'application/json'},
      method:"POST",
      data:{
        phone:wx.getStorageSync('phone')
      },
      dataType:"json",
      success:function(result) {
        //存储用户会员信息
        if(result.data.data.length>0){
          _this.setData({
            vipFlag:true
          })
          wx.setStorageSync('vipFlag',true)
          wx.setStorageSync('vip',JSON.stringify(result.data.data))
          _this.setUserVipInfo(result.data.data)
        }else{
          wx.setStorageSync('vipFlag',false)
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    console.log(12242);
    return {
      title: '来伊份零食会员权益',
      path: 'pages/index/index',
      imageUrl: '/images/share.png'
    }
  },

  getPhone(){
    console.log(245)
    this.setData({
      showAuthPopup:true,
    })
  },
  onGetPhoneNumber(e) {
    if (e.detail.errMsg === 'getPhoneNumber:ok') {
      const { encryptedData, iv } = e.detail;
      wx.login({
        success: res => {
          if (res.code) {
            // 发送 res.code 到后台换取 openid, session_key, unionid
            wx.request({
              url: app.globalData.onlineUrl+"/getUserPhone", // 替换为你的服务器地址
              header:{'content-type': 'application/json'},
              method: 'POST',
              data: {
                code: res.code,
                encryptedData:encryptedData,
                iv:iv,
              },
              success: (response) => {
                console.log(10086,response.data.data.phoneNumber);
                // 存储用户信息
                wx.setStorageSync('phone', response.data.data.phoneNumber);
                wx.setStorageSync('openid', response.data.data.openId);
                this.setUser();
                this.setData(
                  {
                    phone:wx.getStorageSync('phone'),
                    showAuthPopup:false
                  }
                )
                this.getVoucher();
                this.getCouponNum();
              }
            });
          } else {
            console.log('登录失败！' + res.errMsg);
          }
        }
      });
    } else {
      // 用户拒绝授权时的处理（根据合规要求，建议允许用户取消）
      wx.showToast({ 
        title: '需要授权手机号才能使用完整服务', 
        icon: 'none',
        duration: 2000
      });
    }
  },
  setUser:function(){
    let _this=this;
    wx.request({
      url:app.globalData.onlineUrl+"/setUser",
      header:{'content-type': 'application/json'},
      method:"POST",
      data:{
        phone:wx.getStorageSync('phone'),
        openId:wx.getStorageSync('openid')
      },
      dataType:"json",
      complete:function(result) {
        console.log("用户信息更新成功");
      }
    })
  },
  onClosePopup() {
    this.setData({ showAuthPopup: false });
  },
})